# -*- coding: utf-8 -*-

"""
@File    : 00_读取栅格元数据.py
@Author  : fungis@163.com
@notice  : https://mp.weixin.qq.com/s/9oH9Bsw3OWQIRlzY_2o4Ww
"""
import os

from osgeo import gdal, osr


def get_geo_info(FileName):
    if os.path.exists(FileName) is False:
        raise Exception('[Errno 2] 该文件不存在: \'' + FileName + '\'')
    dataset = gdal.Open(FileName, gdal.GA_ReadOnly)
    if dataset == None:
        raise Exception('[Errno 3] 无法读取该文件: \'' + FileName + '\'')

    description = dataset.GetDescription()  # 文件描述
    no_data_value = dataset.GetRasterBand(1).GetNoDataValue()  # 获取无效像元值
    xsize = dataset.RasterXSize  # 读取图像的宽度,x方向上的像素个数
    ysize = dataset.RasterYSize  # 读取图像的高度,y方向上的像素个数
    raster_count = int(dataset.RasterCount)  # 总像元数
    print('数据的大小（行/height，列/weight, RasterCount）：')
    print('(%s %s %s)' % (xsize, ysize, raster_count))
    geo_transform = dataset.GetGeoTransform()  # 获取地理空间信息
    projection = osr.SpatialReference()
    projection.ImportFromWkt(dataset.GetProjectionRef())
    data_type = dataset.GetRasterBand(1).DataType
    data_type = gdal.GetDataTypeName(data_type)
    # print('数据的类型{}'.format(data_type))
    return no_data_value, xsize, ysize, geo_transform, projection, data_type


if __name__ == '__main__':
    raster_path = r'./data-use/tif/NDVI_201405_bm.tif'
    info = get_geo_info(raster_path)
    for k in info:
        print(k)
